package com.zzhrtech.wgzx_cityzen.ui.task;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.overlay.WalkRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.R;

public class TaskMapActivity extends BaseActivity implements RouteSearch.OnRouteSearchListener, LocationSource, AMapLocationListener {

    MapView mMapView;
    AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private RouteSearch routeSearch;
    private String points;

    private boolean isFirst = true;
    private double mLati,mLongi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_map);


        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        toolbar.setNavigationIcon(R.mipmap.ic_close);
        points = getIntent().getStringExtra("point");

        initMap();
    }


    /**
     * 初始化AMap对象
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();


            setUpMap();

            routeSearch = new RouteSearch(this);//初始化routeSearch 对象
            routeSearch.setRouteSearchListener(this);//设置数据回调监听器

            //更改可视区域
            String[] lats = points.split(",");
            LatLng latLng = new LatLng(Double.parseDouble(lats[1]),Double.parseDouble(lats[0]));

            CameraUpdate update = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                    latLng, 17, 30, 0));
            aMap.moveCamera(update);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            aMap.addMarker(markerOptions);

        }
    }

    private void suanlu(){
        String[] lats = points.split(",");
        LatLonPoint endPoint = new LatLonPoint(Double.parseDouble(lats[1]),Double.parseDouble(lats[0]));

        LatLonPoint startPoint = new LatLonPoint(mLati,mLongi);

        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                startPoint, endPoint);
        RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo, RouteSearch.WalkDefault);//初始化query对象，fromAndTo是包含起终点信息，walkMode是步行路径规划的模式
        routeSearch.calculateWalkRouteAsyn(query);//开始算路
    }


    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
//        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // aMap.setMyLocationType()

    }



    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
        Log.d("here==========","wa3lk");

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
        Log.d("here==========","wal4k");

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {


        final WalkPath walkPath = walkRouteResult.getPaths()
                .get(0);
        WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(
                this, aMap, walkPath,
                walkRouteResult.getStartPos(),
                walkRouteResult.getTargetPos());
        walkRouteOverlay.removeFromMap();
        walkRouteOverlay.setNodeIconVisibility(false);
        walkRouteOverlay.addToMap();
        walkRouteOverlay.zoomToSpan();

        Log.d("here==========","walk");
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置是否只定位一次,默认为false
            mLocationOption.setOnceLocation(false);
            //设置为高精度定位模式,Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {

        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

        if (mListener != null && aMapLocation != null) {




            Log.d("loc=========","here");


            if (aMapLocation.getErrorCode() == 0) {

                if (isFirst){
                    mLati = aMapLocation.getLatitude();//获取纬度
                    mLongi = aMapLocation.getLongitude();//获取经度
                    isFirst = false;

                    suanlu();

                    CameraUpdate update = CameraUpdateFactory.zoomTo(17);
                    aMap.moveCamera(update);

                    update = CameraUpdateFactory.changeTilt(30);
                    aMap.moveCamera(update);


                }

                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点



            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode()+ ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }
    }
}
